import router from "./router";
import store from "./store";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import { Message } from "element-ui";
import { getToken } from "@/utils/auth"; // getToken from cookie

NProgress.configure({ showSpinner: false }); // NProgress configuration

const whiteList = ["/login"]; // 不重定向白名单
router.beforeEach(async (to, from, next) => {
  NProgress.start();
  if (getToken()) {
    if (to.path === "/login") {
      next({ path: "/" });
      NProgress.done(); // if current page is dashboard will not trigger	afterEach hook, so manually handle it
    } else {
      if (store.getters.roles.length === 0) {
        try {
          // 拉取用户信息
          const { data } = await store.dispatch("GetInfo");
          // 生成动态路由
          const accessRoutes = await store.dispatch(
            "permission/generateRoutes",
            data.roles
          );
          // dynamically add accessible routes
          router.addRoutes(accessRoutes);
          next({ ...to, replace: true });
        } catch (err) {
          store.dispatch("FedLogOut").then(() => {
            Message.error(err || "登录超时,请重新登录!");
            next({ path: "/" });
          });
        }
      } else {
        next();
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/login?redirect=${to.path}`); // 否则全部重定向到登录页
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  NProgress.done(); // 结束Progress
});
